using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using viBook.Common;
using Telerik.Web.Mvc.Extensions;

namespace viBook.Models
{
    public class ChapterRepository : IChapterRepository
    {
        viBookContext context = new viBookContext();

        public IQueryable<Chapter> All
        {
            get { return context.Chapters; }
        }

        public IQueryable<Chapter> AllIncluding(params Expression<Func<Chapter, object>>[] includeProperties)
        {
            IQueryable<Chapter> query = context.Chapters;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Chapter Find(int id)
        {
            var chapter = context.Chapters.Find(id);
            var totalComments = context.Comments.Where(c => c.ChapterId == id);
            var comments = totalComments.OrderByDescending(c => c.CreatedDate).Take(Constant.MaximunCommentPerChapter);
            var noOfComments = QueryableExtensions.Count(totalComments);
            if (chapter != null)
            {
                chapter.Comments = comments;
                chapter.NumberOfComments = noOfComments;
            }
            return chapter;
        }

        public void InsertOrUpdate(Chapter chapter)
        {
            if (chapter.Id == default(int))
            {
                // New entity
                context.Chapters.Add(chapter);
            }
            else
            {
                // Existing entity
                context.Entry(chapter).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var chapter = context.Chapters.Find(id);
            context.Chapters.Remove(chapter);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

    public interface IChapterRepository
    {
        IQueryable<Chapter> All { get; }
        IQueryable<Chapter> AllIncluding(params Expression<Func<Chapter, object>>[] includeProperties);
        Chapter Find(int id);
        void InsertOrUpdate(Chapter chapter);
        void Delete(int id);
        void Save();
    }
}